package com.rankeiot.core.util;

import cn.hutool.core.thread.ThreadFactoryBuilder;

import java.util.concurrent.*;


/**
 * 前端任务管理
 *
 * @author desire
 */
public class FrontendTaskManager {

//    private static final Cache<String, BaseFrontendTask> TASK_CACHE = createCache();
    private static final ExecutorService TASK_POOL = createTaskPool();

//    private static Cache<String, BaseFrontendTask> createCache() {
//        //任务缓存缓存5分钟,获取后更新时间,如果5分钟内没有处理就移除
//        Cache<String, BaseFrontendTask> cache = new TimedCache<>(5 * 60 * 1000);
//        cache.setListener((key, o) -> {
//            //如果任务还没有结束,需要把任务加回去
//            if (!o.isFinished()) {
//                cache.put(key, o);
//            }
//        });
//        return cache;
//    }

    private static ExecutorService createTaskPool() {
        return new ThreadPoolExecutor(0,
                Integer.MAX_VALUE,
                60L,
                TimeUnit.SECONDS,
                new SynchronousQueue<>(),
                new ThreadFactoryBuilder().setNamePrefix("frontend-ui-task").build(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    public static String start(BaseFrontendTask task) {
        String id = IDUtil.base64UUID();
        invoke(id, task);
        return id;
    }

    /**
     * @param signId 签名ID,同一个ID的任务不会同时运行，类似一个任务的业务锁
     * @param task 前端运行的任务
     * @return 任务ID
     */
    public static String start(String signId, BaseFrontendTask task) {
//        if (TASK_CACHE.containsKey(signId)) {
//            return signId;
//        }
//        invoke(signId, task);
        return signId;
    }

    public static BaseFrontendTask getTask(String taskId) {
//        BaseFrontendTask task = TASK_CACHE.get(taskId, true);
//        if (task != null && task.isFinished()) {
//            TASK_CACHE.remove(taskId);
//        }
//        return task;
        return null;
    }

    private static void invoke(String id, BaseFrontendTask task) {
        task.setId(id);
        //TASK_CACHE.put(id, task);
        Future<?> f = TASK_POOL.submit(() -> {
            try {
                task.run();
            } catch (Exception e) {
                task.setErrorInfo(e.getMessage());
            } finally {
                task.setPercent(100);
                task.setFinished(true);
            }
        });
        task.setFuture(f);
    }

}
